package be.kuleuven.peno3.mobiletoledo.view.multiplechoice;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import be.kuleuven.peno3.mobiletoledo.R;
import be.kuleuven.peno3.mobiletoledo.Data.Client.MultipleChoiceClient;
import be.kuleuven.peno3.mobiletoledo.model.User;

public class AddQuestion extends Activity {
	private Button submit, addAnswer;
	private EditText edit;
	private LinearLayout answerList;
	private int course_id;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.multiplechoiceaddquestion);
		
		course_id = this.getIntent().getExtras().getInt("course_id");
		
		answerList=(LinearLayout) findViewById(R.string.addanswerlist);
		submit=(Button) findViewById(R.string.askquestionbutton);
		edit=(EditText) findViewById(R.string.editquestion);
		addAnswer=(Button) findViewById(R.string.addanswerbutton);
		
		submit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String question = edit.getText().toString();
				
				String possibleAnswers="";
				for (int i=0;i<answerList.getChildCount();i++) {
					if(((EditText)answerList.getChildAt(i)).getText().toString().length()!=0) {
						possibleAnswers+=((EditText)answerList.getChildAt(i)).getText().toString()+"|||";
					}
				}
				try {
					possibleAnswers=possibleAnswers.substring(0,possibleAnswers.length()-3);
				}
				catch(StringIndexOutOfBoundsException ex) {
					Toast.makeText(AddQuestion.this.getApplicationContext(), "Gelieve antwoordmogelijkheden toe te voegen", Toast.LENGTH_SHORT).show();
					return;
				}
				
				if(!MultipleChoiceClient.addQuestion(question, User.getInstance().getUsername(), course_id, possibleAnswers)) {
					Toast.makeText(AddQuestion.this.getApplicationContext(), "Er is geen internetverbinding", Toast.LENGTH_SHORT).show();
					finish();
				}
				
				//exit the Activity
				try {
					finish();
				} catch (Throwable e) {
					e.printStackTrace();
				}
			}
		});
		
		addAnswer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				addPossibleAnswer();
			}
		});
		
		for(int i=0;i<2;i++) {
			addPossibleAnswer();
		}
	}
	
	/**
	 * Adds a EditText View to the list of possible answers
	 */
	private void addPossibleAnswer() {
		answerList.addView(new EditText(AddQuestion.this), new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
	}
}
